package com.xinxing.city.recovery.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Paint;
import android.graphics.Rect;
import android.hardware.Camera;
import android.os.Environment;
import android.os.Handler;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;

import com.elvishew.xlog.XLog;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.hikvision.netsdk.HCNetSDK;
import com.hikvision.netsdk.INT_PTR;
import com.hikvision.netsdk.NET_DVR_JPEGPARA;
import com.xinxing.city.recovery.Constant;
import com.xinxing.city.recovery.MainActivity;
import com.xinxing.city.recovery.R;
import com.xinxing.city.recovery.RecoveryApplication;
import com.xinxing.city.recovery.Tools;
import com.xinxing.city.recovery.entitys.HkCamera;
import com.xinxing.city.recovery.hk.Hk;
import com.xinxing.city.recovery.hk.SDKGuider;
import com.xinxing.city.recovery.net.OkHttpRequest;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class VideoSet {
    //    private SurfaceView m_surfaceView = null;
    private SurfaceHolder m_surfaceView_holder = null;
    private SurfaceView m_surfaceView2 = null;
    private int m_iPreviewHandle = -1;
    private Button start;
    private Context context;
    private MainActivity mainActivity;
    private SharedPreferences sharedPreferences;
    private Camera camera;
    private Camera.Parameters parameters;
    private SurfaceHolder mSurfaceHolder;

    private Integer position = 0;
    private SurfaceHolder holder;
    private Gson gson;
    private String codeYz = "";
    private String videoUrl;
    public String token;

    //普通摄像头
    private List<String> imageUrl = new ArrayList<>();
    private Integer imageF = 1;
    private Integer imageJc = 1; //1 开始 2 开始摄像头 3 保存图片
    private Boolean isLoad = false;
    private Boolean isLoads = false;
    private Handler handler = null;
    private Boolean isRecode = true;
    private Runnable runnable;
    private Integer imageNum;

    //海康摄像头
    private Handler handler1 = null;
    private Boolean isRecode1 = true;
    private Runnable runnable1;
    private Integer imageNum1;
    private List<String> imageUrl1 = new ArrayList<>();
    private Integer imageF1 = 1;
    private Integer imageJc1 = 1; //1 开始 2 开始摄像头 3 保存图片
    private int lUserID = -1;
    public VideoSet(Context cont) {
        context = cont;
        mainActivity = (MainActivity) cont;
        gson = new Gson();

        sharedPreferences = context.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
        position = sharedPreferences.getInt("camera_id", 0);

//        m_surfaceView = mainActivity.findViewById(R.id.SuView);
//        mSurfaceHolder = m_surfaceView.getHolder();
        m_surfaceView2 = mainActivity.findViewById(R.id.HkView);
//        initSurface();
        Hk();
    }

    //海康
    private void Hk() {
        start = mainActivity.findViewById(R.id.button_preview_start);
        holder = m_surfaceView2.getHolder();
        //m_surfaceView2.setZOrderOnTop(true);

        try {

            String str = (String) SharedPreferencesUtils.getParam(context, "hk_camera", "");
            if (!str.equals("")) {
                Type dev = new TypeToken<HkCamera>() {
                }.getType();
                Gson gson = new Gson();
                ;
                HkCamera hkCamera = gson.fromJson(str, dev);
                Hk hk = new Hk(context, hkCamera.getUserIp(), hkCamera.getUserName(), hkCamera.getUserPassward(), hkCamera.getPort());
                lUserID = hk.initVideo();
            } else {
                if (!Constant.MOCK) {
                    Hk hk = new Hk(context, "192.168.1.64", "admin", "Xx135246", "8000");
                    lUserID = hk.initVideo();
                }
            }

//            Handler handler = new Handler();
//            Runnable runnable = new Runnable() {
//                @Override
//                public void run() {
//                    //m_surfaceView2.setZOrderOnTop(true);
//                    m_surfaceView2.setVisibility(View.VISIBLE);
//                    SDKGuider.g_sdkGuider.m_comPreviewGuider.RealPlaySurfaceChanged_jni(m_iPreviewHandle, 0, holder);
//                    NET_DVR_PREVIEWINFO struPlayInfo = new NET_DVR_PREVIEWINFO();
//                    struPlayInfo.lChannel = 1;
//                    struPlayInfo.dwStreamType = 0;
//                    struPlayInfo.bBlocked = 1;
//                    struPlayInfo.hHwnd = m_surfaceView2.getHolder();
//                    m_iPreviewHandle = SDKGuider.g_sdkGuider.m_comPreviewGuider.RealPlay_V40_jni(0,struPlayInfo, null);
//                    handler.removeCallbacks(this);
//                }
//            };
//            handler.postDelayed(runnable,1000);
        } catch (Exception e) {

        }

    }

    public void initSurface() {
        mSurfaceHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder surfaceHolder) {
                Log.e("12345612", "aa");
            }

            @Override
            public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
                Log.e("12345634", "bb");
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
                Log.e("12345656", "ff");
            }
        });
    }

    //监控
    public void videoStart(Integer i) {
        try {
            if (camera != null) stopCamera(0);
            camera = Camera.open(i);
            startCamera(0, mSurfaceHolder);
            imageJc = 2;
            isLoad = false;
        } catch (Exception e) {
            camera = null;
            initCar();
            e.printStackTrace();
        }
    }

    private void startCamera(int cameraId, SurfaceHolder holder) {

        if (camera != null) {
            try {
                parameters = camera.getParameters();
                parameters.setPictureFormat(ImageFormat.JPEG);
                parameters.setPreviewSize(1920, 1080);
                parameters.setPictureSize(1920, 1080);
                parameters.setPreviewFrameRate(30);
                camera.setParameters(parameters);
                camera.setPreviewDisplay(holder);
                camera.startPreview();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void stopCamera(int cameraId) {
        if (camera != null) {
            camera.stopPreview();
            camera.release();
            camera = null;
        }
    }

    //
    private void setImageVideo() {

        //上报交投数据到服务端
        if (imageF == 4 && imageF1 == 4) {
            close();
            Map<String, Object> par = new HashMap<>();
            par.put("code", codeYz);
            List<JsonObject> appendixs = new ArrayList<>();

            for (int i = 0; i < imageUrl.size(); i++) {
                JsonObject item = new JsonObject();
                item.addProperty("type", "image");
                item.addProperty("originName", "截图");
                item.addProperty("isOut", "n");
                item.addProperty("path", imageUrl.get(i).toString());
                appendixs.add(item);
            }

            for (int i = 0; i < imageUrl1.size(); i++) {
                JsonObject item = new JsonObject();
                item.addProperty("type", "image");
                item.addProperty("originName", "截图");
                item.addProperty("isOut", "t");
                item.addProperty("path", imageUrl1.get(i).toString());
                appendixs.add(item);
            }

            par.put("appendixs", appendixs);

            //LogFileUtils.logToFile(gson.toJson(appendixs));

            OkHttpRequest okHttpRequest = new OkHttpRequest(mainActivity.getApplicationContext(), mainActivity.getSupportFragmentManager());
            okHttpRequest.sendPostRequestN("/sr-recycling/v1/01/recycle/inspect_appendix/create", gson.toJson(par), token, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {

                }
            });

        }

    }

    //截图
    // 创建一个PictureCallback来处理截图数据
    private Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            String path = context.getExternalFilesDir(null).getAbsolutePath() + "image" + imageNum + ".jpg";
            File file = new File(path);

            try (OutputStream os = new FileOutputStream(file)) {
                // 处理截图数据，保存到文件或进行其他操作
                Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);


                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);


                File file2 = new File(path);
                test(file2);
                saveBitmapToFile(file2);

                os.flush();
            } catch (Exception e) {
                initCar();
                e.printStackTrace();
            }

        }
    };

    // 执行截图操作
    public void takePicture(int num, int bucketNum, String code) {

        //海康
//        SDKGuider.g_sdkGuider.m_comConfGuider.Test_CaptureJpegPicture_jni(0,1);
        //

        codeYz = code;
        imageNum = num;
        if (num == 1) {
            imageF = 1;
            imageUrl = new ArrayList<>();
        }

        //删除旧文件
        String path = context.getExternalFilesDir(null).getAbsolutePath() + "image" + imageNum + ".jpg";
        File file = new File(path);
        if (file.exists() == true) {
            file.delete();
        }

        if (handler == null) {
            handler = new Handler();
            runnable = new Runnable() {
                @Override
                public void run() {
                    //判断截图是否完成
                    if (imageF <= imageNum) {

                        if (imageJc == 1) { //判断截图流程
                            //获取等待开启
                            if (!isLoad) { //判断流程是否在进行中
                                videoStart(bucketNum - 1);
                            }
                        } else if (imageJc == 2) { //判断截图流程
                            if (!isLoads && camera != null) {
                                isLoads = true;
                                camera.takePicture(null, null, mPictureCallback);
                            }
                        }

                        handler.postDelayed(this, 1500);

                    } else if (imageF == 4) {
                        handler.removeCallbacks(this);
                        handler = null;
                        setImageVideo();
                    } else {
                        handler.postDelayed(this, 1500);
                    }
                }
            };
            handler.postDelayed(runnable, 1500);
        }
    }

    // 执行截图操作
    public void takePicture1(int num, String code) {

        codeYz = code;
        imageNum1 = num;

        if (num == 1) {
            imageF1 = 1;
            imageUrl1 = new ArrayList<>();
        }
        Log.e("kong", "海康拍照" + 1);
        //删除旧文件
        String filePath = context.getExternalFilesDir(null).getAbsolutePath() + "/imaget" + imageNum1 + ".jpg";
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }
        SDKGuider.g_sdkGuider.m_comPreviewGuider.RealPlay_Stop_jni(m_iPreviewHandle);
//        m_surfaceView.setVisibility(View.INVISIBLE);
        refreshThread(filePath);
    }

    private void refreshThread(String path) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                NET_DVR_JPEGPARA PARA = new NET_DVR_JPEGPARA();
                PARA.wPicQuality = 0;
                PARA.wPicSize = 13;
                int iBufferSize = 2448 * 2048;
                byte[] sbuffer = new byte[iBufferSize];
                INT_PTR bytesRerned = new INT_PTR();
                Log.e("kong", "海康拍照" + 2);
                boolean flag = HCNetSDK.getInstance().NET_DVR_CaptureJPEGPicture_NEW(lUserID, 1, PARA, sbuffer, iBufferSize, bytesRerned);
                if (flag) {
                    Log.e("kong", "海康拍照" + 3);
                    Bitmap bitmap = BitmapFactory.decodeByteArray(sbuffer, 0, sbuffer.length);
                    try {
                        saveFile(bitmap, path);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                } else {
                    Log.e("photo", "error");
//                    XLog.e("NET_DVR_ERROR:" + HCNetSDK.getInstance().NET_DVR_GetLastError());
                }
            }
        }).start();
    }

    /**
     * 保存文件
     *
     * @param bm
     * @param fileName
     * @throws IOException
     */
    public boolean saveFile(Bitmap bm, String fileName) throws IOException {
        File myCaptureFile = new File(fileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
        File file = new File(fileName);
        Log.e("kong", "海康拍照" + 4);
        if (file.exists()) {
            saveBitmapToFile1(file);
        } else {
            XLog.e("海康文件不存在");
        }
        return true;
    }

    public void test(File file) throws IOException {
        Bitmap b = BitmapFactory.decodeFile(file.getPath());
        Bitmap newB = addTextWatermark(b, 20, Color.RED, 0, 0, true);


        File myCaptureFile = new File(file.getPath());
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        newB.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();

    }

    // 保存Bitmap到文件
    public void saveBitmapToFile(File file) {


        OkHttpRequest okHttpRequest = new OkHttpRequest(context, mainActivity.getSupportFragmentManager());

        okHttpRequest.sendFileRequestN("/sr-asset/v1/assets", file, token, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("photo", "桶外 onFailure" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                JsonObject res = okHttpRequest.getResData();
                if (res == null) return;
                imageUrl.add(res.get("data").getAsString());

            }
        });

    }

    public void saveBitmapToFile1(File file) {
        try {
            Log.e("photo", "桶外saveBitmapToFile   " + file.getPath());
            OkHttpRequest okHttpRequest = new OkHttpRequest(context, mainActivity.getSupportFragmentManager());
            okHttpRequest.sendFileRequestN("/sr-asset/v1/assets", file, token, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("photo", "桶外 onFailure" + e.toString());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {

                    JsonObject res = okHttpRequest.getResData();
                    if (res == null) return;
                    Log.e("photo", "海康图片提交成功");
                    imageUrl1.add(res.get("data").getAsString());
                    Log.e("photo", "桶外 " + res.get("data").getAsString() + "    " + Constant.imageUrl.size());
                }
            });

        } catch (Exception e) {
            initCar1();
        }

    }

    //录像操作
    public void hkStartRecode() {
        videoUrl = "";
        Boolean as = SDKGuider.g_sdkGuider.m_comPreviewGuider.RealPlay_Record(m_iPreviewHandle, 1, "/sdcard/recordings.mp4");
        if (as) {
            Log.e("录像开启", "录像开启" + HCNetSDK.getInstance().NET_DVR_GetLastError());
            isRecode = true;
        } else {
            isRecode = false;
            Log.e("录像开启失败", "录像失败");
        }
    }

    public void hkStopRecode(HkStopRecodeBack hkStopRecodeBack) {
        if (isRecode) {
            Boolean dd = SDKGuider.g_sdkGuider.m_comPreviewGuider.RealPlay_Stop_jni(m_iPreviewHandle);
            if (dd) {
                isRecode = false;
                OkHttpRequest okHttpRequest = new OkHttpRequest(context, mainActivity.getSupportFragmentManager());
                File file = new File("/sdcard/recordings.mp4");
                okHttpRequest.sendFileRequest("/sr-asset/v1/assets", file, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        JsonObject res = okHttpRequest.getResData();
                        if (res == null) return;
                        videoUrl = res.get("data").getAsString();
                        hkStopRecodeBack.onSuccess(videoUrl);
                    }
                });
            } else {
                Log.e("录像完毕出错", "录像完毕");
            }
        } else {
            Log.e("录像开启失败", "录像失败");
        }
    }

    public interface HkStopRecodeBack {
        void onSuccess(String url);
    }

    //初始化下一次操作
    public void initCar() {
        imageF++;
        imageJc = 1;
        isLoad = false;
        isLoads = false;
    }

    public void initCar1() {
        imageF1++;
        imageJc1 = 1;
    }

    //关闭摄像头信息
    public void close() {
        imageF = 1;
        imageJc = 1;

        imageF1 = 1;
        imageJc1 = 1;

        if (handler != null && runnable != null) handler.removeCallbacks(runnable);
        if (handler1 != null && runnable1 != null) handler1.removeCallbacks(runnable1);
        if (camera != null) stopCamera(0);

        handler = null;
        runnable = null;
        handler1 = null;
        runnable1 = null;

        isLoad = false;
    }

    //隐藏
    private void vHide() {
        //m_surfaceView.setVisibility(View.INVISIBLE);
        //m_surfaceView2.setVisibility(View.INVISIBLE);
    }

    /**
     * 给图片添加水印 当需要换行的时候，推荐使用StaticLayout 这种实现方式
     *
     * @param src      原bitmap
     * @param textSize 文字大小
     * @param x        距离图片位图的左边距
     * @param y        距离图片位图的上边距
     * @param recycle  是否回收bitmap，建议true
     */
    public Bitmap addTextWatermark(Bitmap src, int textSize, int color, float x, float y, boolean recycle) {
        Objects.requireNonNull(src, "src is null");
        Bitmap ret = src.copy(src.getConfig(), true);
        TextPaint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
        Canvas canvas = new Canvas(ret);
        paint.setColor(color);
        paint.setTextSize(80);
        Rect bounds = new Rect();
        String content = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        /*
        单行文字的实现代码
        paint.getTextBounds(content, 0, content.length(), bounds);
        canvas.drawText(content, x, y, paint);*/

        canvas.translate(x, y);
        StaticLayout myStaticLayout = new StaticLayout(content, paint, canvas.getWidth(), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
        myStaticLayout.draw(canvas);

//        canvas.drawBitmap(bitmap, 0, 0, null);//绘制小图片使用的代码
        if (recycle && !src.isRecycled()) src.recycle();
        return ret;
    }

    public void test() {
        Log.e("photo", "test()" + imageUrl.size() + "  ----  " + Constant.imageUrl.size());
        Map<String, Object> par = new HashMap<>();
        par.put("code", RecoveryApplication.getInstance().getYhCode());
        List<JsonObject> appendixs = new ArrayList<>();

        for (int i = 0; i < Constant.imageUrl.size(); i++) {
            JsonObject item = new JsonObject();
            item.addProperty("type", "image");
            item.addProperty("originName", "截图");
            item.addProperty("isOut", "n");
            item.addProperty("path", Constant.imageUrl.get(i).toString());
            appendixs.add(item);
        }

        for (int i = 0; i < imageUrl1.size(); i++) {
            JsonObject item = new JsonObject();
            item.addProperty("type", "image");
            item.addProperty("originName", "截图");
            item.addProperty("isOut", "t");
            item.addProperty("path", imageUrl1.get(i).toString());
            appendixs.add(item);
        }

        par.put("appendixs", appendixs);

        //LogFileUtils.logToFile(gson.toJson(appendixs));
        Log.e("photo", "test()   " + gson.toJson(par) + " token " + RecoveryApplication.getInstance().getToken());
        OkHttpRequest okHttpRequest = new OkHttpRequest(mainActivity.getApplicationContext(), mainActivity.getSupportFragmentManager());
        okHttpRequest.sendPostRequestN("/sr-recycling/v1/01/recycle/inspect_appendix/create", gson.toJson(par), RecoveryApplication.getInstance().getToken(), new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("photo", "test()  onFailure " + gson.toJson(par) + " token " + token);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e("photo", "test()   chenggong");
                imageF = 1;
            }
        });

    }

}
